import { getHost } from '@/store/system/utils';
import useUserStore from '@/store/user';
import { getToken } from '@/store/user/utils';
import { SOCKET_FUNCTION } from '../enum/websocket.enum';

export enum SOCKET_ENUM {
  CONNECTING,
  OPEN,
  CLOSING,
  CLOSED,
}
/* 系统状态控制 */
export const pageStatus = ref<'maintenance' | 'normal'>('normal');
// WEBSOCKET实例
export const websocket = ref<WebSocket>();
// 重连次数
export const retryTimes = ref(0);
/**
 * @description: 发送信息
 * @param {string} data
 */
export const sendMsg = (data: string) => {
  if (!websocket) return;

  const userInfo = useUserStore();
  let msg: SocketOnline = {
    data,
    time: new Date().toDateString(),
    username: userInfo.$state.userInfo?.nickName,
    type: 'ONLINE',
  };
  websocket.value?.send(JSON.stringify(msg));
};

export const connectWs = () => {
  const host = getHost();
  const token = getToken();
  let url = '';
  if (host.startsWith('http')) {
    url = host.replace('http', 'ws');
  } else if (host.startsWith('https')) {
    url = host.replace('https', 'wss');
  }
  retryTimes.value++;
  websocket.value = new WebSocket(
    url + `${SOCKET_FUNCTION.ONLINE}?Authorization=${token}&time=${retryTimes.value}`,
  );
  return websocket.value;
};
